# -*- coding: utf-8 -*-
#*******************************************************************************
#   
#   http://www.ccmanhua.com/manhua/\d+/ 解析器                                  
# 
#*******************************************************************************
from base import *

tag='ccmnahua'

#---------------------------- 验证模块 ----------------------------

def url_judgement(url):
    if re.match(r'http://www.ccmanhua.com/manhua/\d+/',url):
        return valid_check(url)
    return False

def valid_check(url):
    print('{} catch {}'.format(tag,url))
    content=request_for(url,common_headers);
    if content:
        content=content.decode('utf-8')
        if re.compile(r'<h1>(.*?)</h1>',re.M|re.S).findall(content)[0]=='':
            return False
        return get_loader(url)
    return False

def get_loader(url):
    return CcmanhuaLoader(url,CcmanhuaPageParser,CcmanhuaVolParser)

#---------------------------- 下载器 ----------------------------

class NyasoLoader(ComicLoader):
    def __init__(self,url,comic_page_parser,comic_vol_parser):
        super().__init__(url,comic_page_parser,comic_vol_parser)

#----------------------------  解析器  ----------------------------

class CcmanhuaPageParser(ComicPageParser):
    def __init__(self,comic):
        super().__init__(comic)
        self.site_prefix='http://www.ccmanhua.com'
    def work(self,content):
        # title
        self.comic.title=re.compile(r'<h1>(.*?)</h1>').findall(content)[0]
        # description
        self.comic.description=re.compile('<div id="intro-all" class="none"><p style="text-indent:2em;">(.*?)</p>',re.S|re.M).findall(content)[0]
        # cover
        self.comic.cover=re.compile(r'<p class="hcover"><img(.*?)src="(.*?)"').findall(content)[0][1]
        # vols
        vols_content=re.compile(r'<div class="chapter-list cf mt10" id="chpater-list-1">(.*?)</div>',re.S|re.M).findall(content)[0]
        self.feed(vols_content)
    def handle_starttag(self,tag,attrs):
        if tag=='a':
            infos={}
            for (v,k) in attrs:
                infos[v]=k
            self.comic.vols.append(InfoVol(self.site_prefix+infos['href'],infos['title']))

class CcmanhuaVolParser(ComicVolParser):
    def __init__(self):
        super().__init__()
    def work(self,content):
        img_prefix='http://img.danmeiwo.com'
        urls=re.compile(r"fs':  \[(.*?)\]",re.S|re.M).findall(content)[0]
        for url in urls.split(','):
            url=url.replace('"','').replace('\\','')
            self.pic_urls.append((img_prefix+url,zero_prefix(self.pic_index)))
            self.pic_index+=1
